package org.example.springaitest.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Configuration
public class AiConfig {
    ChatMemory chatMemory = MessageWindowChatMemory.builder().build();
    @Value("classpath:/prompt.txt")  // 使用classpath前缀，从类路径根目录加载
    private Resource promptResource;  // 注入为Resource类型

    @Autowired
    VectorStore vectorStore;

    @Bean
    ChatClient chatClient(ChatClient.Builder builder, @Qualifier("vectorStore") VectorStore store, Advisor neo4jRagAdvisor) throws IOException {
        // 读取Resource内容
        String promptContent = new String(
                promptResource.getInputStream().readAllBytes(),
                StandardCharsets.UTF_8
        );
        PromptTemplate promptTemplate = new PromptTemplate(promptContent);
        return builder
                .defaultSystem(promptTemplate.getTemplate())
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
//                .defaultAdvisors(QuestionAnswerAdvisor.builder(vectorStore).searchRequest(SearchRequest.builder().similarityThreshold(0.8d).topK(6).build()).build()
                .defaultAdvisors(neo4jRagAdvisor)
                .build();

    }
}
